/**
* @description 全局公共方法
*/
import { isFunction, isObject, isArray, isDate } from '@/utils/is.js'


/**
 * @description 深度克隆
 * @param obj 克隆对象
 * @returns _obj 经过克隆之后的对象
 */
 export const cloneDeep = function(obj) {
  // 常见的非值直接返回
  if ([null, undefined, NaN, false].includes(obj)) return obj
  // 原始类型直接返回
  if (!isFunction(obj) && !isObject(obj)) return obj
  const o = isArray(obj) ? [] : {}
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      o[key] = isObject(obj[key]) ? cloneDeep(obj[key]) : obj[key]
    }
  }
  return o
}

/**
* @description 序列化对象参数
* @param { Object } obj
* @returns { String } str
*/
export const setObjToString = function(obj) {
  if (Object.keys(obj).length <= 0) return ''
  let parameters = ''
  for (const key in obj) {
    parameters += key + '=' + encodeURIComponent(obj[key]) + '&'
  }
  parameters = parameters.replace(/&$/, '')
  return '?' + parameters
}

/***
 * @description 格式化日期
 * @param time
 * @param formatStr 符号
 * @param flag 是否返回YYYY-MM-DD HH:mm:ss true 返回，false返回没有时间的日期
 * @returns {string | null}
 */
 export const formatDate = function(val, formatStr, flag) {
  const date = new Date(val)
  if (!isDate(date)) throw new Error('参数不能转化为时间')
  const year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  month = month < 10 ? `0${month}` : month
  day = day < 10 ? `0${day}` : day
  if (flag) {
    let hours = date.getHours()
    let minutes = date.getMinutes()
    let seconds = date.getSeconds()
    hours = hours < 10 ? `0${hours}` : hours
    minutes = minutes < 10 ? `0${minutes}` : minutes
    seconds = seconds < 10 ? `0${seconds}` : seconds
    return `${year}${formatStr}${month}${formatStr}${day}${formatStr} ${hours}:${minutes}:${seconds}`
  } else {
    return `${year}${formatStr}${month}${formatStr}${day}`
  }
}

/***
 * @description 格式化距离当前前后的时间
 * @param num
 * @param formatStr 符号
 * @param flag 是否返回YYYY-MM-DD HH:mm:ss
 * @returns {string | null}
 */
 export const distanceFormatDate = function(num, formatStr, flag) {
  if (!isNumber(num)) throw new Error('距离的日期只能为数字')
  const date = new Date()
  const targetdayMilliseconds = date.getTime() + 1000 * 60 * 60 * 24 * num
  const distanceDate = formatDate(targetdayMilliseconds, formatStr, flag)
  return {
    currentDate: formatDate(date, formatStr, flag),
    distanceDate
  }
}

// #ifdef H5
/**
* @description: H5复制粘贴方法
* @param {type} content 复制内容
* @return: res
*/
export function ClipCopy(content) {
  let res = null;
  let textarea = document.createElement("textarea");
  textarea.value = content;
  textarea.readOnly = "readOnly";
	document.body.appendChild(textarea);
  textarea.select(); // 选中文本内容
  textarea.setSelectionRange(0, textarea.value.length);
  res = document.execCommand("copy");
	textarea.remove();
  return res;
}
// #endif
